package com.tsfyun.common.base.help;

import com.google.common.collect.Maps;
import com.tsfyun.common.base.support.HttpServletRequestWrapper;
import eu.bitwalker.useragentutils.DeviceType;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

public class RequestUtils {

    private RequestUtils() {
    }

    private static final String UNKNOWN = "unknown";

    public static String getRequestJsonString(HttpServletRequest request) throws IOException {
        String method = request.getMethod();
        String contentType = com.tsfyun.common.base.util.StringUtils.null2EmptyWithTrim(request.getContentType());
        HttpServletRequestWrapper sqlRequest = null;
        if (request instanceof HttpServletRequest) {
            method = request.getMethod();
            sqlRequest = new HttpServletRequestWrapper(request);
        }
        //JSON请求
        if ("POST".equalsIgnoreCase(method) && contentType.contains("application/json")) {
            //此处需要注意流只能读一次
            HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request);
            return wrapper.getRequestBodyParame();
        } else {
            Map<String,Object> paramsMap = Maps.newHashMap();
            Map  paramMap = sqlRequest.getParameterMap();
            Iterator entries = paramMap.entrySet().iterator();
            Map.Entry entry;
            String name = "";
            String value = "";
            while (entries.hasNext()) {
                entry = (Map.Entry) entries.next();
                name = (String) entry.getKey();
                Object valueObj = entry.getValue();
                if(null == valueObj){
                    value = "";
                }else if(valueObj instanceof String[]){
                    String[] values = (String[])valueObj;
                    for(int i = 0;i < values.length; i++){
                        value = values[i] + ",";
                    }
                    //去掉最后一个逗号
                    value = value.substring(0, value.length()-1);
                }else{
                    //其他参数则直接转字符串
                    value = valueObj.toString();
                }
                paramsMap.put(name, value);
            }
            return paramsMap.toString();
        }
    }


    /**
     * =
     * 获取访问设备
     *
     * @return
     */
    public static String obtainDevice(HttpServletRequest request) {
        String ua = request.getHeader("User-Agent");
        if (StringUtils.isEmpty(ua)) {
            return null;
        }
        UserAgent userAgent = UserAgent.parseUserAgentString(ua);
        OperatingSystem os = userAgent.getOperatingSystem();
        //未知登录设备
        if (DeviceType.UNKNOWN != os.getDeviceType()) {
            return os.getDeviceType().getName();
        }
        return null;
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}